package query

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/go-sqlx/model"
	"github.com/jmoiron/sqlx"
	"log"
)

func GetUser(db *sqlx.DB, id int) (model.User, error) {
	var user model.User
	err := db.Get(&user, "SELECT id, user_name, email FROM sys_user WHERE id=?", id)
	return user, err
}

func GetAllUsers(db *sqlx.DB) ([]model.User, error) {
	var users []model.User
	err := db.Select(&users, "SELECT id, user_name, email FROM sys_user")
	return users, err
}

func GetUsersByIds(db *sqlx.DB, ids []int) ([]model.User, error) {
	query, args, err := sqlx.In("SELECT * FROM sys_user WHERE id IN (?)", ids)
	if err != nil {
		return nil, err
	}

	query = db.Rebind(query)
	var users []model.User
	err = db.Select(&users, query, args...)
	return users, err
}

func PrepareQuery(db *sqlx.DB) {
	stmt, err := db.Preparex("SELECT * FROM sys_user WHERE id = ?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	var user model.User
	err = stmt.Get(&user, 1)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", user)
}
